<script lang="tsx">
import { defineComponent, computed, ref, onMounted } from 'vue';
import { VbenAvatar, VbenIcon, Badge } from '@vben-core/shadcn-ui';
import { useUserStore } from '@vben/stores';
import { updateUserInfoApi } from '#/api/system/user';
import { getUserCertificateCountForPersonCenterApi } from '#/api/personal/certification';
import { ElMessage } from 'element-plus';
import { $t } from '@vben/locales';
import { useRouter } from 'vue-router';
import {
  FileBadge,
  SvgCertificationIcon,
  SvgCourseIcon,
  SvgExamIcon,
  SvgCertificateIcon,
  SvgInfoIcon,
  SvgNoticeIcon
} from '@vben/icons';
import userIcon from '#/assets/images/user-img.png';
import RealnameDialog from './modules/realname-dialog.vue';
import { useMessage } from '../../hooks/useMessage';
import { avatarList } from './const';

export default defineComponent({
  name: 'PersonalHome',
  setup() {
    const userStore = useUserStore();
    const router = useRouter();
    const { badgeCount } = useMessage();

    const userInfo = computed(() => userStore.userInfo);

    // 证书数量
    const certificateCount = ref(0);

    // 实名认证弹窗状态
    const realnameDialogVisible = ref(false);

    // 打开实名认证弹窗
    const openRealnameDialog = () => {
      realnameDialogVisible.value = true;
    };

    // 实名认证确认回调
    const handleRealnameConfirm = (data: any) => {
      // 这里可以处理实名认证成功后的逻辑，比如刷新用户信息
    };

    // 功能卡片数据 - 改为计算属性以支持响应式更新
    const functionCards = computed(() => [
      {
        title: $t('personal.myCertification'),
        icon: SvgCertificationIcon,
        iconColor: 'text-[#1677FF]',
        bgColor: 'bg-[#1677FF33]',
        route: '/lesson/personalCenter/certification'
      },
      {
        title: $t('personal.myCourses'),
        icon: SvgCourseIcon,
        iconColor: 'text-[#13C2C2]',
        bgColor: 'bg-[#13C2C233]',
        route: '/lesson/personalCenter/courses'
      },
      {
        title: $t('personal.myExams'),
        icon: SvgExamIcon,
        iconColor: 'text-[#D77E11]',
        bgColor: 'bg-[#FFA94033]',
        route: '/lesson/personalCenter/exams'
      },
      {
        title: $t('personal.myCertificates'),
        icon: SvgCertificateIcon,
        iconColor: 'text-[#9254DE]',
        bgColor: 'bg-[#9254DE33]',
        route: '/lesson/personalCenter/certificates'
      },
      {
        title: $t('personal.personalInfo'),
        icon: SvgInfoIcon,
        iconColor: 'text-[#52C41A]',
        bgColor: 'bg-[#52C41A33]',
        route: '/lesson/personalCenter/personalProfile'
      },
      {
        title: $t('personal.myMessages'),
        icon: SvgNoticeIcon,
        iconColor: 'text-[#0067D1]',
        bgColor: 'bg-[#3674CC33]',
        badge: badgeCount.value,
        route: '/lesson/personalCenter/userMessage'
      }
    ]);

    const handleCardClick = (route: string) => {
      router.push(route);
    };

    // 更新头像
    const handleUpdateAvatar = async (avatar: string) => {
      try {
        await updateUserInfoApi({ icon: avatar });
        // 更新用户store中的头像
        if (userStore.userInfo) {
          userStore.setUserInfo({
            ...userStore.userInfo,
            icon: avatar
          });
        }
        ElMessage.success($t('personal.avatarUpdateSuccess'));
      } catch (error) {
        throw error; // 重新抛出错误，让组件处理
      }
    };

    // 处理头像更新错误
    const handleAvatarError = (message: string) => {
      ElMessage.error(message);
    };

    // 获取证书数量
    const getCertificateCount = async () => {
      try {
        const data = await getUserCertificateCountForPersonCenterApi();
        certificateCount.value = data || 0;
      } catch (error) {
        console.error('获取证书数量失败:', error);
        certificateCount.value = 0;
      }
    };

    // 组件挂载时获取证书数量
    onMounted(() => {
      getCertificateCount();
    });

    return () => (
      <div class="h-full">
        <div class="flex h-full gap-[16px]">
          {/* 左侧用户信息卡片 */}
          <div class="w-[300px] bg-white rounded-[8px] p-[24px]">
            <div class="flex flex-col items-center">
              <VbenAvatar
                class="w-[128px] h-[128px]"
                src={userInfo.value?.icon || userIcon}
                alt={userInfo.value?.nameCn || $t('common.userTxt')}
                editable={true}
                updateAvatar={handleUpdateAvatar}
                onError={handleAvatarError}
                avatarList={avatarList}
              />
              <div class="text-center mb-6 w-full">
                {/* 实名状态标签和按钮 */}
                <div class="flex items-center justify-center mb-2 mt-[12px]">
                  {userInfo.value?.isRealName ? (
                    <span class="inline-block px-2 py-0.5 text-xs rounded bg-green-100 text-green-700 border border-green-200 mr-2">
                      {$t('personal.realNameVerified')}
                    </span>
                  ) : (
                    <div class="relative">
                      <span class="inline-block px-2 py-0.5 text-xs rounded bg-[#FA541C33] text-[#C8481D]">
                        {$t('personal.realNameUnverified')}
                      </span>
                      <el-button
                        link={true}
                        type="primary"
                        class="absolute top-0 right-[-48px]"
                        onClick={openRealnameDialog}
                      >
                        {$t('personal.goRealName')}
                      </el-button>
                    </div>
                  )}
                </div>
                <div class="text-[18px] font-semibold text-gray-900 mb-2 truncate">
                  {userInfo.value?.nameCn || '-'}
                </div>
                <div class="text-[14px] text-gray-500 truncate">
                  {userInfo.value?.phone || '-'}
                </div>
              </div>
              <span class="flex items-center gap-[4px] h-[40px] bg-[#E9DDF8] rounded-[20px] px-[14px]">
                <VbenIcon icon={SvgCertificateIcon} class="w-[16px] h-[16px] fill-transparent" />
                <span class="text-[14px] text-[#191919] font-normal">{$t('personal.ownedCertificates')}</span>
                <span class="text-[14px] text-[#191919] font-normal">{certificateCount.value || '-'}</span>
              </span>
            </div>
          </div>

          {/* 右侧功能卡片区域 */}
          <div class="flex-1 bg-white rounded-[8px] p-[24px]">
            <div class="grid grid-cols-3 gap-6">
              {functionCards.value.map((card, index) => (
                <div
                  key={index}
                  onClick={() => handleCardClick(card.route)}
                  class={`
                  relative cursor-pointer rounded-[8px] py-[25px] px-[20px]
                  hover:scale-[1.02] transition-all duration-300
                  flex items-center h-[120px] gap-[12px]
                  border-[1px] border-solid border-[#DCDFE6]
                `}
                >
                  {/* 图标 */}
                  <div class={`${card.bgColor} ${card.iconColor} p-[15px] rounded-[50%]`}>
                    <VbenIcon icon={card.icon} class="w-10 h-10 fill-transparent" />
                  </div>

                  {/* 标题 */}
                  <div class="text-[16px] font-medium text-center text-[#191919]">
                    {card.title}
                  </div>
                  {/* 徽章 */}
                  {!!card.badge && (
                    <div
                      class="text-[#000000] ml-auto text-[18px] font-normal"
                    >
                      {card.badge}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* 实名认证弹窗 */}
        <RealnameDialog
          v-model={realnameDialogVisible.value}
          onConfirm={handleRealnameConfirm}
        />
      </div>
    );
  }
});
</script>
